# -*- coding: utf-8 -*-

##Container是整个数据库的外壳，里边包含表格，用户信息，权限设置等
import Service.Service as Service
import re
import json
from Data.Table import Table,Data,Field,tableStruct
import Service.Service as Service
import Engine.Engine as Engine
class Container:
    tables_=[]
    Orders_=[]
    sql=None
    Authority_ = False #权限
    engines = Engine.Engine()
    Field_ = Field(None,None,None)
    tableStruct_, Data_ = None,None
    def __init__(self):
        self.pwd_ = ["ROOT"] #密码集合
        self.User_ = ["ROOT"] #用户名集合
    def LoginValidate(self):#登陆验证
        User = raw_input("请输入用户名：")
        pwd = raw_input("请输入密码：")
        if (User==self.User_[0])and(pwd == self.pwd_[0]):
            print "Welcome to New_SQL!"
            return True
        else:
            print "账号密码输入错误,请重新输入！"
            self.LoginValidate()
            return False
    def ChangeAuthority(self):      #self.Authority_ = True
        print self.Authority_
    def isEmpty(self,sql):
        SQL = sql.split()
        if SQL == '':
            return False
        else:
            return True
    def read_file_to_ram(self):
        try:
            with open("../Data/db.emp", "r") as json_file:
                tablestruct=json.load(json_file)
                json_file.close()
            return tablestruct
        except:
            return []
    def isQuit(self,sql):
        quit_="^EXIT|QUIT$"
        is_quit = re.match(quit_,sql,re.I)
        if is_quit != None:
            return True
        else:
            return False
    def write_to_file(self, tablestructs):
        tables_ = []
        try:
            if tablestructs != None:
                for t in tablestructs:
                    tables_.append(t)
                with open("../Data/db.emp", "w") as json_file:
                    #json.dump(tables_, json_file, indent=4)
                    json_file.write(json.dumps(tables_, indent=4))
                #print is_exists
                print "保存成功..."
                json_file.close()
                #return tables_
        except:
            print "保存失败..."
    def is_table_exists(self, tablestruct, table):
        ta = tableStruct(None, None, None, None)
        engines = Engine.Engine()
        for i in tablestruct:
            ta.__dict__ = engines.class_to_dict(i)
            if ta.name_ == table.name_:
                print "The table is existed!"
                return True
            else:
                return False
    def desc_table(self, tablestructs, name):
        ta = tableStruct(None, None, None, None)
        for table in tablestructs:
            ta.__dict__= self.engines.class_to_dict(table)
            if ta.name_ == name:
                print json.dumps(self.engines.class_to_dict(ta), indent=4)
                break
    def drop_column(self, tablestructs, co_name, ta_name):
        ta = tableStruct(None, None, None, None)
        ts = []
        field_=[]
        for table in tablestructs:
            ta.__dict__ = self.engines.class_to_dict(table)
            if ta.name_ == ta_name:
                for field in ta.fields_:
                    self.Field_.__dict__ = field
                    if self.Field_.name_ == co_name:
                        print "删除成功..."
                        continue
                    field_.append(self.Field_)
                ta.fields_=[]
                ta.fields_=self.engines.class_to_dict(field_)
            ts.append(ta)
        return ts
if __name__ == '__main__':
    Contains = Container()
    Engines = Engine.Engine()
    Services = Service.Service()
    tab=None
    E=[]
    tab1=tableStruct(None,None,None,None)
    EE = []
    tabstr = Contains.read_file_to_ram()
    E = Engines.dict_to_class(tabstr, tableStruct(None, None, None, None))
    Contains.LoginValidate()
    while True:
        sql=raw_input("New_SQL>:")
        if Contains.isEmpty(sql) != True:
            continue
        if Contains.isQuit(sql):
            print "Bye!"
            break
        tabstr = Contains.read_file_to_ram()
        E = Engines.dict_to_class(tabstr, tableStruct(None, None, None, None))
        for i in E:
            EE.append(Engines.dict_to_class(i, tableStruct(None, None, None, None)))
        if Engines.is_Alter(sql):
            if Services.is_add(sql):
                continue
            elif Services.is_drop(sql):
                column_name = Services.get_drop_column(sql)
                table_name = Services.get_alter_table_name(sql)
                tabs = Contains.drop_column(EE, column_name, table_name)
                EE = tabs
                Contains.write_to_file(Engines.class_to_dict(tabs))
                continue
        elif Engines.is_Create(sql):
            tab = Engines.CreateTable(sql)
            if Contains.is_table_exists(EE, tab):
                continue
            EE.append(tab)
            Contains.write_to_file(Engines.class_to_dict(EE))
        elif Services.is_desc(sql):
            name = Services.get_desc_name(sql)
            Contains.desc_table(EE, name)
        #Contains.write_to_file(Engines.class_to_dict(EE))

